package com.mt.api.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import java.nio.charset.Charset;

/**
 * Created by plover on 2018/5/18.
 */
@Slf4j
public class HttpClientUtils {
    private static PoolingHttpClientConnectionManager connectionManager = null;
    private static HttpClientBuilder httpBuilder = null;
    private static RequestConfig requestConfig = null;

    private static int MAXCONNECTION = 10;
    private static int DEFAULTMAXCONNECTION = 5;

    private static String IP = "www.baidu.com";
    private static int PORT = 80;

    static {
        //设置http的状态参数
        requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000)
                .setConnectTimeout(30000)
                .setConnectionRequestTimeout(30000)
                .build();

        HttpHost target = new HttpHost(IP, PORT);
        connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(MAXCONNECTION);//客户端总并行链接最大数
        connectionManager.setDefaultMaxPerRoute(DEFAULTMAXCONNECTION);//每个主机的最大并行链接数
        connectionManager.setMaxPerRoute(new HttpRoute(target), 20);
        httpBuilder = HttpClients.custom();
        httpBuilder.setConnectionManager(connectionManager);
    }

    public static CloseableHttpClient getConnection() {
        CloseableHttpClient httpClient = httpBuilder.build();
        return httpClient;
    }

    public static String sendPost(JSONObject data, String url) {
        String result = "";
        HttpClient client = getConnection();
        try {
            HttpUriRequest post = getRequestMethod(data, url, "post");
            HttpResponse response = client.execute(post);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity, "utf-8");
                log.info("请求接口结果, URL:{}, 参数:{}, 结果:{}", url, data, result);
            } else {
                log.error("请求接口响应错误, URL:{}, 参数:{}, 结果:{}", url, data, JSON.toJSONString(response));
            }
        } catch (Exception e) {
            log.error("请求接口异常, URL:{}, 参数:{}, 结果:{}", url, data, result, e);
        } finally {
            return result;
        }
    }

    public static String sendPost(String url) {
        String result = "";
        try {
            HttpClient client = getConnection();
            HttpUriRequest post = getRequestMethod(new JSONObject(), url, "post");
            HttpResponse response = client.execute(post);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity, "utf-8");
                log.info("请求接口结果, URL:{}, 结果:{}", url, result);
            } else {
                log.error("请求接口响应错误, URL:{}, 结果:{}", url, JSON.toJSONString(response));
            }
        } catch (Exception e) {
            log.error("请求接口异常, URL:{}, 参数:{}, 结果:{}", url, result, e);
        } finally {
            return result;
        }
    }

    public static String sendGet(String url) {
        String result = "";
        try {
            HttpClient client = getConnection();
            HttpUriRequest get = getRequestMethod(new JSONObject(), url, "get");
            HttpResponse response = client.execute(get);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity, "utf-8");
                log.info("请求接口结果, URL:{}, 结果:{}", url, result);
            } else {
                log.error("请求接口响应错误, URL:{}, 结果:{}", url, JSON.toJSONString(response));
            }
        } catch (Exception e) {
            log.error("请求接口异常, URL:{}, 结果:{}", url, result, e);
        } finally {
            return result;
        }
    }

    public static String sendGet(JSONObject data, String url) {
        String result = "";
        try {
            HttpClient client = getConnection();
            HttpUriRequest get = getRequestMethod(data, url, "get");
            HttpResponse response = client.execute(get);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(entity, "utf-8");
                log.info("请求接口结果, URL:{}, 参数:{}, 结果:{}", url, data, result);
            } else {
                log.error("请求接口响应错误, URL:{}, 参数:{}, 结果:{}", url, data, JSON.toJSONString(response));
            }
        } catch (Exception e) {
            log.error("请求接口异常, URL:{}, 参数:{}, 结果:{}", url, data, result, e);
        } finally {
            return result;
        }
    }


    public static HttpUriRequest getRequestMethod(JSONObject data, String url, String method) {
        HttpUriRequest reqMethod = null;
        if ("post".equalsIgnoreCase(method)) {
            reqMethod = RequestBuilder.post().setUri(url)
                    .setEntity(new StringEntity(data.toJSONString(), Charset.forName("UTF-8")))
                    .setConfig(requestConfig).build();
        } else if ("get".equalsIgnoreCase(method)) {
            reqMethod = RequestBuilder.get().setUri(url)
                    .setEntity(new StringEntity(data.toJSONString(), Charset.forName("UTF-8")))
                    .setConfig(requestConfig).build();
        }
        reqMethod.setHeader("Content-Type", "application/json");
        reqMethod.setHeader("charset", "UTF-8");
        return reqMethod;
    }

    // public static void main(String args[]) throws IOException {
    //     JSONObject object = new JSONObject();
    //     object.put("barcode", "567886318274_4+2记录");
    //     String url = "http://127.0.0.1:9000/test/req";
    //     // HttpUriRequest request = RequestBuilder.post().setUri(url).setEntity(new StringEntity(object.toJSONString(), Charset.forName("UTF-8")))
    //     //         .setConfig(requestConfig).build();
    //     // request.setHeader("Content-Type", "application/json");
    //     // request.setHeader("charset", "UTF-8");
    //     // HttpClient client = getConnection();
    //     // HttpResponse response = client.execute(request);
    //     // String result = null;
    //     // if (response.getStatusLine().getStatusCode() == 200) {
    //     //     HttpEntity entity = response.getEntity();
    //     //     result = EntityUtils.toString(entity, "utf-8");
    //     //     log.info("请求接口结果, URL:{}, 结果:{}", url, result);
    //     // } else {
    //     //     log.error("请求接口响应错误, URL:{}, 结果:{}", url, JSON.toJSONString(response));
    //     // }
    //     // System.out.println(result);
    //     String r = sendPost(object, url);
    //     System.out.println(r);
    // }
}
